package com.wcpdoc.exam.api.controller;

import com.wcpdoc.base.util.CurLoginUserUtil;
import com.wcpdoc.core.controller.BaseController;
import com.wcpdoc.core.entity.PageIn;
import com.wcpdoc.core.entity.PageOut;
import com.wcpdoc.core.entity.PageResult;
import com.wcpdoc.core.entity.PageResultEx;
import com.wcpdoc.core.exception.MyException;
import com.wcpdoc.core.util.ValidateUtil;
import com.wcpdoc.exam.core.cache.QuestionCache;
import com.wcpdoc.exam.core.entity.*;
import com.wcpdoc.exam.core.service.MyCollectService;
import com.wcpdoc.exam.core.service.QuestionService;
import com.wcpdoc.exam.core.util.QuestionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 我的收藏控制层
 * 
 */
@Controller
@RequestMapping("/api/myCollect")
public class ApiMyCollectController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(ApiMyCollectController.class);
	
	@Resource
	private MyCollectService collectService;
	@Resource
	private QuestionService questionService;
//	@Resource
//	private QuestionTypeService questionTypeService;

	/**
	 * 我的收藏列表
	 * 
	 * @return pageOut
	 * type  1错题，2收藏
	 */
	@RequestMapping("/listpage")
	@ResponseBody
	public PageResult listpage(Integer type) {
		try {
			if (!ValidateUtil.isValid(type)) {
				throw new MyException("type error");
			}
			PageIn pageIn = new PageIn(request);
			pageIn.addAttr("curUserId", getCurUser().getId());
			pageIn.addAttr("type", type);
//			pageIn.addAttr("questionTypeId", questionTypeId);
			PageOut pageOut = collectService.getListpage(pageIn);
			return PageResultEx.ok().data(pageOut);
		} catch (Exception e) {
			log.error("我的收藏列表错误：", e);
			return PageResult.err();
		}
	}
	
	/**
	 * 收藏获取
	 *
	 * @return pageOut
	 */
//	@RequestMapping("/get")
//	@ResponseBody
//	public PageResult get(Integer myCollectId) {
//		try {
//			MyCollect myCollect = collectService.getEntity(myCollectId);
//			if (!(CurLoginUserUtil.isSelf(myCollect.getUpdateUserId()) || CurLoginUserUtil.isAdmin())) {
//				throw new MyException("无操作权限");
//			}
//			return PageResultEx.ok()
//					.addAttr("id", myCollect.getId())
//					.addAttr("name", myCollect.getName())
//					.addAttr("questionTypeId", myCollect.getQuestionTypeId())
//					.addAttr("questionTypeName", questionTypeService.getEntity(myCollect.getQuestionTypeId()).getName())
//					.addAttr("startTime", DateUtil.formatDateTime(myCollect.getStartTime()))
//					.addAttr("endTime", DateUtil.formatDateTime(myCollect.getEndTime()))
//					.addAttr("rmkState", myCollect.getRmkState())
//					;
//		} catch (MyException e) {
//			log.error("收藏删除错误：{}", e.getMessage());
//			return PageResult.err().msg(e.getMessage());
//		} catch (Exception e) {
//			log.error("收藏删除错误：", e);
//			return PageResult.err();
//		}
//	}
	
	/**
	 * 我的收藏试题
	 * 
	 * @param myCollectId
	 * @param questionId
	 * @return PageResult
	 */
	@RequestMapping("/question")
	@ResponseBody
	public PageResult question(Integer myCollectId, Integer questionId) {
		try {
			// 数据校验
			MyCollect myCollect = collectService.getEntity(myCollectId);
//			if (myCollect.getState() == 0) {
//				throw new MyException("已删除");
//			}
//			long curTime = System.currentTimeMillis();
//			if (!(myCollect.getStartTime().getTime() < curTime && curTime < myCollect.getEndTime().getTime())) {
//				throw new MyException("时间已过期");
//			}
//			Set<Integer> userIdSet = new HashSet<>();
//			userIdSet.addAll(Arrays.asList(myCollect.getUserIds()));
//			if (ValidateUtil.isValid(userIdSet) && !userIdSet.contains(getCurUser().getId())) {
//				throw new MyException("无权限");
//			}
			if (!(CurLoginUserUtil.isSelf(myCollect.getUpdateUserId()) || CurLoginUserUtil.isAdmin())) {
				throw new MyException("无操作权限");
			}
			// 试题获取
			Map<String, Object> questionMap = new HashMap<>();
			Question question = QuestionCache.getQuestion(questionId);
			questionMap.put("id", question.getId());
			questionMap.put("type", question.getType());
			questionMap.put("markType", question.getMarkType());
			questionMap.put("title", question.getTitle());
			questionMap.put("markOptions", question.getMarkOptions());
			questionMap.put("score", question.getScore());
			questionMap.put("analysis", question.getAnalysis());
			questionMap.put("userAnswer", myCollect.getUserAnswer());
			questionMap.put("collectId", myCollect.getId());
			{// 试题选项
				List<String> options = new ArrayList<>();
				if (QuestionUtil.hasSingleChoice(question) || QuestionUtil.hasMultipleChoice(question)) {
					List<QuestionOption> questionOptionList = QuestionCache.getOption(question.getId());
					for (QuestionOption questionOption : questionOptionList) {
						options.add(questionOption.getOptions());
					}
				}
				questionMap.put("options", options);
			}
			{// 试题答案
				List<QuestionAnswer> questionAnswerList = QuestionCache.getAnswer(question.getId());
				List<Object> answers = new ArrayList<>();
				List<BigDecimal> scores = new ArrayList<>();
				for(QuestionAnswer answer : questionAnswerList) {
					if (QuestionUtil.hasSingleChoice(question) 
							|| QuestionUtil.hasTrueFalse(question) 
							|| (QuestionUtil.hasQA(question) && QuestionUtil.hasSubjective(question))) {
						answers.add(answer.getAnswer());
					} else if (QuestionUtil.hasMultipleChoice(question)) {
						Collections.addAll(answers, answer.getAnswer().split(","));
						scores.add(answer.getScore());
					} else if (QuestionUtil.hasFillBlank(question) 
							|| (QuestionUtil.hasQA(question) && QuestionUtil.hasObjective(question))) {
						answers.add(answer.getAnswer());
						scores.add(answer.getScore());
					}
				}
				questionMap.put("answers", answers);
				questionMap.put("scores", scores);
			}
			return PageResultEx.ok().data(questionMap);
		} catch (MyException e) {
			log.error("我的收藏试题错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		}  catch (Exception e) {
			log.error("我的收藏试题错误：", e);
			return PageResult.err();
		}
	}

	/**
	 * 收藏添加
	 *
	 * @param myCollect
	 * @return PageResult
	 */
	@RequestMapping("/addAndUpdate")
	@ResponseBody
	public PageResult addAndUpdate(MyCollect myCollect) {
		try {
			Question question = QuestionCache.getQuestion(myCollect.getQuestionId());
			myCollect.setUserId(getCurUser().getId());
			myCollect.setQuestionTypeId(question.getQuestionTypeId());
			myCollect.setType(2);
//			if (ValidateUtil.isValid(myCollect.getUserAnswer())) {
//				String[] userAnswers = myCollect.getUserAnswer().split(",");
//				List<String> userAnswerList = new ArrayList<>();
//				Collections.addAll(userAnswerList,userAnswers);
//				myCollect.setUserAnswer(userAnswerList);
//			}
			collectService.addCollect(myCollect);
			return PageResult.ok();
		} catch (MyException e) {
			log.error("添加错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		}  catch (Exception e) {
			log.error("添加错误：", e);
			return PageResult.err();
		}
	}

	/**
	 * 收藏删除
	 *
	 * @return pageOut
	 */
	@RequestMapping("/del")
	@ResponseBody
	public PageResult del(Integer id) {
		try {
			if(!ValidateUtil.isValid(id)){
				throw new MyException("id error");
			}
			collectService.del(id);
			return PageResult.ok();
		} catch (MyException e) {
			log.error("删除错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		}  catch (Exception e) {
			log.error("删除错误：", e);
			return PageResult.err();
		}
	}

	/**
	 * 根据试题id删除收藏
	 *
	 * @return pageOut
	 */
	@RequestMapping("/delByQuestionId")
	@ResponseBody
	public PageResult delByQuestionId(Integer questionId) {
		try {
			if(!ValidateUtil.isValid(questionId)){
				throw new MyException("id error");
			}
			collectService.delByQuestionId(questionId,getCurUser().getId(),2);
			return PageResult.ok();
		} catch (MyException e) {
			log.error("删除错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		}  catch (Exception e) {
			log.error("删除错误：", e);
			return PageResult.err();
		}
	}

	
	/**
	 * 我的收藏试题列表
	 * 
	 * @return PageResult
	 */
	@RequestMapping("/questionList")
	@ResponseBody
	public PageResult questionList(Integer questionTypeId,Integer type) {
		try {
			// 数据有效性校验
//			MyCollect myCollect = collectService.getEntity(myCollectId);
//			if (myCollect.getState() == 0) {
//				throw new MyException("无权限");
//			}
//			long curTime = System.currentTimeMillis();
//			if (!(myCollect.getStartTime().getTime() < curTime && curTime < myCollect.getEndTime().getTime())) {
//				throw new MyException("时间已过期");
//			}
//			Set<Object> userIdSet = new HashSet<>();
//			userIdSet.addAll(Arrays.asList(myCollect.getUserIds()));
//			if (ValidateUtil.isValid(userIdSet) && !userIdSet.contains(getCurUser().getId())) {
//				throw new MyException("无权限");
//			}
			if (!(CurLoginUserUtil.isSelf(getCurUser().getId()) || CurLoginUserUtil.isAdmin())) {
				throw new MyException("无操作权限");
			}

			// 试题列表

			List<MyCollect> questionIds = collectService.getIds(questionTypeId,type,getCurUser().getId());
			return PageResultEx.ok().data(questionIds);
		} catch (MyException e) {
			log.error("我的收藏试题列表错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		}  catch (Exception e) {
			log.error("我的收藏试题列表错误：", e);
			return PageResult.err();
		}
	}

	/**
	 * 我的收藏试卷
	 *type 1题库，2题型
	 * @return PageResult
	 */
	@RequestMapping("/paper")
	@ResponseBody
	public PageResult paper(Integer type,Integer questionTypeId) {
		try {
			// 校验数据有效性
			if (!ValidateUtil.isValid(type)) {
				throw new MyException("参数错误");
			}
			List<Map<String, Object>> _myExam = collectService.getPaperByType(type,getCurUser().getId(),questionTypeId);

			if (_myExam == null) {
				throw new MyException("无查阅权限");
			}

			// 组装试卷
			List<Map<String, Object>> paper = new ArrayList<>();
//			List<Integer> myQuestionList = exerService.getPaperByQuestionType(getCurUser().getId());

			for (Map<String, Object> item : _myExam) {

				Map<String, Object> myQuestion = new HashMap<>();
//				myQuestion.put("type", _myQuestion.getType());
//				myQuestion.put("questionId", _myQuestion.getQuestionId());
//				Question question = QuestionCache.getQuestion(_myQuestion.getQuestionId());// 已关联考试的试题不会改变，缓存起来加速查询。
				myQuestion.put("questionId", item.get("id"));
				myQuestion.put("id", item.get("collectid"));
				myQuestion.put("type", item.get("type"));
				myQuestion.put("title", item.get("title"));
				{// 选项
					List<String> options = new ArrayList<>();
					if (Integer.parseInt(item.get("type").toString())==1 || Integer.parseInt(item.get("type").toString())==2) {// 如果是单选或多选，添加选项字段
						List<QuestionOption> questionOptionList = QuestionCache.getOption(Integer.parseInt(item.get("id").toString()));
						for (QuestionOption questionOption : questionOptionList) {// 常规顺序
							options.add(questionOption.getOptions());
						}
					}
					myQuestion.put("options", options);
				}
				{// 标准答案
					List<String> answerList = new ArrayList<>();
//					List<QuestionAnswer> questionAnswerList = QuestionCache.getAnswer(_myQuestion.getQuestionId());
					String[] questionAnswerList = item.get("answer").toString().split(",");
//					for(String answer : questionAnswerList){
//						if (Integer.parseInt(item.get("type").toString())==2) {
//							String[] answers = answer.getAnswer().split(",");
//							Collections.addAll(answerList, answers);
//						} else  {
//							answerList.add(answer);
//						}
//					}
					if (Integer.parseInt(item.get("type").toString())==2) {
						Collections.addAll(answerList, questionAnswerList);
					} else  {
						answerList.add(item.get("answer").toString());
					}
					myQuestion.put("answers", answerList);
				}
				paper.add(myQuestion);
			}

			return PageResultEx.ok().data(paper);
		} catch (MyException e) {
			log.error("我的试卷错误：{}", e.getMessage());
			return PageResult.err().msg(e.getMessage());
		} catch (Exception e) {
			log.error("我的试卷错误：", e);
			return PageResult.err();
		}
	}
	
}
